package com.chu.controller;

import com.chu.entity.Dept;
import com.chu.entity.Employee;
import com.chu.entity.Role;
import com.chu.enums.PageEnum;
import com.chu.enums.StateEnum;
import com.chu.service.DeptService;
import com.chu.service.EmployeeService;
import com.chu.service.RoleService;
import com.chu.utils.ExcelExport;
import com.chu.utils.ResultVO;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
public class EmployeeController {
    @Autowired
    private EmployeeService service;
    @Autowired
    private DeptService deptService;
    @Autowired
    private RoleService roleService;

    //ajax异步校检用户名
    @RequestMapping("/resource/demo2/checkLoginName")
    public void checkLoginName(String loginname,HttpServletResponse response){
        response.setContentType("application/json;charset=utf-8");
        Employee result = service.findByLoginName(loginname);
        ObjectMapper mapper = new ObjectMapper();
        if(result==null){
            try {
                response.getWriter().write(mapper.writeValueAsString(new ResultVO(0,"用户名可用")));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            try {
                response.getWriter().write(mapper.writeValueAsString(new ResultVO(13,"用户名已经被使用")));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //批量删除
    @RequestMapping("/resource/demo2/deleteBatch")
    public void deleteBatch(int[] empId,HttpServletResponse response,String method){
        response.setContentType("text/html;charset=UTF-8");

        if("deleteBatch".equals(method)){
            try {
                int result = service.deleteBatch(empId);
                PrintWriter write = response.getWriter();
                if(result>0){
                    write.write("<script>alert('删除成功');location.href='/resource/demo2/getusers'</script>");
                }else{
                    write.write("<script>alert('删除失败');location.href='/resource/demo2/getusers'</script>");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else if("exports".equals(method)){
            try {
                //查询被选中的数据信息
                List<Employee> employeeList = service.findAllByIds(empId);
                //导出数据
                ExcelExport.createFilst("用户信息");
                ExcelExport.createOther(employeeList);
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                ExcelExport.exports(new FileOutputStream("F:\\asd\\"+format+".xls"));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    //删除单个用户
    @RequestMapping("/resource/demo2/deleteById")
    public void  deleteById(int id, HttpServletResponse response){
        response.setContentType("text/html;charset=UTF-8");
        //真删除 删除数据库信息 delete
        //这里做假删除 修改信息状态
        try {
            int result = service.deleteByPrimaryKey(id, StateEnum.OFFLINE.getIsLine());

            PrintWriter write = response.getWriter();

            if(result>0){

                write.write("<script>alert('删除成功');location.href='/resource/demo2/getusers'</script>");
            }else{
                write.write("<script>alert('删除失败');location.href='/resource/demo2/getusers'</script>");

            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    //修改用户的信息回显
    @RequestMapping("/resource/demo2/findOneUser")
    public String findOneUser(int id,ModelMap map){

        Employee employee1 = service.selectByPrimaryKey(id);

        map.addAttribute("employee1",employee1);

        List<Dept> deptList = deptService.findAllDept();

        map.addAttribute("deptList",deptList);

        List<Role> roleList = roleService.findAllRole(employee1.getDeptid());

        map.addAttribute("roleList",roleList);

        return "resource/demo2/update";
    }
    //修改用户
    @RequestMapping("/resource/demo2/updateUser")
    public String updateUser(Employee record){
        int result = service.updateByPrimaryKeySelective(record);
        if(result>0){
            return "redirect:/resource/demo2/getusers";
        }else{
            return "resource/demo2/findOneUser?id="+record.getId();
        }
    }


    //增加用户
    @RequestMapping("/resource/demo2/insertEmp")
    public String insertEmp(Employee record){
        record.setCreatedate(new Date());
        record.setState(1);
        int insert = service.insert(record);
        if(insert>0){
            return "redirect:/resource/demo2/getusers";
        }else{
            return "redirect:/resource/demo2/getAllDept";
        }
    }

    //用户管理显示所有用户
    @RequestMapping("/resource/demo2/getusers")
    @RequiresPermissions("user:selectall")//访问该请求的权限code
    public String getUsers(@RequestParam(defaultValue = "1") int page, ModelMap map,
                           String username,String rolename,String deptname){
        PageInfo<Employee> pageInfo =
                service.findAll(page, PageEnum.SIZE.getSize(),username,rolename,deptname);
        map.addAttribute("pageInfo",pageInfo);
        map.addAttribute("uname",username);
        map.addAttribute("rname",rolename);
        map.addAttribute("dname",deptname);

        return "resource/demo2/list";
    }












}
